package user_account

import (
	"database/sql"
	"fmt"
	"jihe.common/protos/user_server/proto"
)

//user_account_pk
func (s *Model) Create(in *proto.UserAccount) (err error) {
	sqlStr := fmt.Sprintf("INSERT INTO %s (uid, total_amount)VALUES($1,$2)", s.Name)
	_, err = s.Db.Exec(sqlStr, in.Uid, in.TotalAmount)
	if err != nil {
		return
	}
	return
}

func (s *Model) AddAmount(in *proto.UserAccount) (err error) {
	sqlStr := fmt.Sprintf("update %s set total_amount = total_amount + $1 where uid = $2", s.Name)
	_, err = s.Db.Exec(sqlStr, in.TotalAmount, in.Uid)
	if err != nil {
		return
	}
	return
}

func (s *Model) SubtractionAmount(in *proto.UserAccount) (err error) {
	sqlStr := fmt.Sprintf("update %s set total_amount = total_amount - $1 where uid = $2", s.Name)
	_, err = s.Db.Exec(sqlStr, in.TotalAmount, in.Uid)
	if err != nil {
		return
	}
	return
}

func (s *Model) GetByUid(uid string) (out *proto.UserAccount, err error) {
	out = new(proto.UserAccount)
	sqlStr := fmt.Sprintf("select uid, total_amount from %s where uid = $1", s.Name)
	err = s.Db.QueryRow(sqlStr, uid).Scan(&out.Uid, &out.TotalAmount)
	if err != nil {
		if err == sql.ErrNoRows {
			err = nil
			return
		}
		return
	}
	return
}
